<script setup>
import ip from '@/utils/baseURL.js';
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import axios from 'axios';
import debounce from 'lodash/debounce';


// API基础URL（后端接口地址）
const apiBaseUrl = ref( ip + '/inter');

// 获取当前用户的 session
const session = localStorage.getItem('session');

// 上传配置
const uploadUrl = computed(() => `${apiBaseUrl.value}/upload`);
const uploadHeaders = {
  "Session": `${session}`
};

// 选项卡状态
const activeTab = ref('teachers');

// 教师相关数据
const teacherList = ref([]);
const teachersLoading = ref(false);
const teacherSearch = ref('');
const teacherPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 学生相关数据
const studentList = ref([]);
const studentsLoading = ref(false);
const studentSearch = ref('');
const studentPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 教师表单
const teacherDialogVisible = ref(false);
const isEditingTeacher = ref(false);
const teacherFormRef = ref(null);
const teacherForm = reactive({
  teacherId: null,
  teacherName: '',
  title: '',
  email: '',
  research: '',
  office: '',
  picture: ''
});

// 学生表单
const studentDialogVisible = ref(false);
const isEditingStudent = ref(false);
const studentFormRef = ref(null);
const studentForm = reactive({
  id: null,
  name: '',
  sex: 1,
  grade: null,
  specialty: '',
  email: '',
  picture: '',
  blog: '',
  direction: '',
  briInfo: '',
  position: '成员',
  attendTime: [],
  attendTimeDate: '',
  qq: '',
  studentId: ''
});

// 提交状态
const submitting = ref(false);

// 表单验证规则
const teacherRules = {
  teacherName: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  title: [{ required: true, message: '请输入职称', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  office: [{ required: true, message: '请输入办公室', trigger: 'blur' }]
};

const studentRules = {
  name: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  grade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
  specialty: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  direction: [{ required: true, message: '请输入研究方向', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

// 记录所有年级的数据
const allGrades = ref([]);

// 年级筛选
const selectedGrade = ref('');
const availableGrades = computed(() => {
  // 使用记录的所有年级数据，而不是从当前筛选后的studentList中提取
  return allGrades.value.sort((a, b) => b - a);
});

// 处理年级变化
const handleGradeChange = () => {
  studentPagination.currentPage = 1;
  loadStudents();
};

// 处理选项卡切换
const handleTabClick = () => {
  if (activeTab.value === 'teachers') {
    loadTeachers();
  } else {
    loadStudents();
  }
};

// 排序状态
const sortConfig = reactive({
  prop: '', // 排序字段
  order: '' // 排序方向：ascending / descending
});

// 处理表格排序变化
const handleSortChange = ({ prop, order }) => {
  console.log('排序变化:', prop, order);
  sortConfig.prop = prop;
  sortConfig.order = order;
  
  // 刷新学生列表，带上排序参数
  studentPagination.currentPage = 1;
  loadStudents();
};

// 加载教师数据
const loadTeachers = async () => {
  teachersLoading.value = true;
  try {
    const response = await axios.get(`${apiBaseUrl.value}/teacherInfo/getInfo`);
    
    if (response.data.code === 200) {
      const allTeachers = response.data.data.records || [];
      
      // 如果有搜索关键词，过滤教师列表
      let filteredTeachers = allTeachers;
      if (teacherSearch.value) {
        const keyword = teacherSearch.value.toLowerCase();
        filteredTeachers = allTeachers.filter(teacher => 
          teacher.teacherName.toLowerCase().includes(keyword) ||
          teacher.title.toLowerCase().includes(keyword) ||
          teacher.research.toLowerCase().includes(keyword)
        );
      }
      
      teacherPagination.total = filteredTeachers.length;
      
      // 分页处理
      const startIdx = (teacherPagination.currentPage - 1) * teacherPagination.pageSize;
      const endIdx = startIdx + teacherPagination.pageSize;
      teacherList.value = filteredTeachers.slice(startIdx, endIdx);
    } else {
      ElMessage.error(response.data.message || '加载教师数据失败');
    }
  } catch (error) {
    console.error('加载教师数据错误:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    teachersLoading.value = false;
  }
};

// 加载学生数据 - 更新以支持年级筛选、动态年级列表和排序功能
const loadStudents = async () => {
  studentsLoading.value = true;
  try {
    const response = await axios.get(`${apiBaseUrl.value}/userInfo/getInfo`);
    
    if (response.data.code === 200) {
      const allStudents = response.data.data.records || [];
      
      // 从获取的数据中提取所有可用的年级，并存储在全局变量中
      const gradeSet = new Set();
      allStudents.forEach(student => {
        if (student.grade) {
          gradeSet.add(student.grade);
        }
      });
      // 更新全局年级列表
      allGrades.value = Array.from(gradeSet);
      
      // 应用筛选条件
      let filteredStudents = allStudents;
      
      // 1. 如果有搜索关键词，过滤学生列表
      if (studentSearch.value) {
        const keyword = studentSearch.value.toLowerCase();
        filteredStudents = filteredStudents.filter(student => 
          student.name.toLowerCase().includes(keyword) ||
          student.specialty.toLowerCase().includes(keyword) ||
          student.direction.toLowerCase().includes(keyword)
        );
      }
      
      // 2. 如果选择了年级，进一步过滤
      if (selectedGrade.value) {
        filteredStudents = filteredStudents.filter(student => 
          student.grade === selectedGrade.value || student.grade === String(selectedGrade.value)
        );
      }
      
      // 3. 应用排序（如果有指定排序参数）
      if (sortConfig.prop && sortConfig.order) {
        filteredStudents.sort((a, b) => {
          let valueA, valueB;
          
          if (sortConfig.prop === 'grade') {
            // 年级排序
            valueA = parseInt(a.grade) || 0;
            valueB = parseInt(b.grade) || 0;
          } else if (sortConfig.prop === 'attendTime') {
            // 加入时间排序
            valueA = a.attendTime && a.attendTime.length === 3 ? 
              new Date(a.attendTime[0], a.attendTime[1]-1, a.attendTime[2]) : new Date(0);
            valueB = b.attendTime && b.attendTime.length === 3 ? 
              new Date(b.attendTime[0], b.attendTime[1]-1, b.attendTime[2]) : new Date(0);
          } else {
            // 默认排序字段
            valueA = a[sortConfig.prop];
            valueB = b[sortConfig.prop];
          }
          
          if (sortConfig.order === 'ascending') {
            return valueA > valueB ? 1 : -1;
          } else {
            return valueA < valueB ? 1 : -1;
          }
        });
      } else {
        // 默认按加入时间降序排序
        filteredStudents.sort((a, b) => {
          // 获取日期数组
          const dateA = a.attendTime && a.attendTime.length === 3 ? 
            new Date(a.attendTime[0], a.attendTime[1]-1, a.attendTime[2]) : new Date(0);
          const dateB = b.attendTime && b.attendTime.length === 3 ? 
            new Date(b.attendTime[0], b.attendTime[1]-1, b.attendTime[2]) : new Date(0);
          
          // 降序排序 (晚的日期排在前面)
          return dateB - dateA;
        });
      }
      
      studentPagination.total = filteredStudents.length;
      
      // 分页处理
      const startIdx = (studentPagination.currentPage - 1) * studentPagination.pageSize;
      const endIdx = startIdx + studentPagination.pageSize;
      studentList.value = filteredStudents.slice(startIdx, endIdx);
    } else {
      ElMessage.error(response.data.message || '加载学生数据失败');
    }
  } catch (error) {
    console.error('加载学生数据错误:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    studentsLoading.value = false;
  }
};

// 搜索防抖
const debounceTeacherSearch = debounce(() => {
  teacherPagination.currentPage = 1;
  loadTeachers();
}, 300);

const debounceStudentSearch = debounce(() => {
  // 这里因为学生数据是前端分页，我们需要重新加载并筛选数据
  studentPagination.currentPage = 1;
  loadStudents();
}, 300);

// 添加教师
const handleAddTeacher = () => {
  isEditingTeacher.value = false;
  Object.keys(teacherForm).forEach(key => {
    teacherForm[key] = key === 'teacherId' ? null : '';
  });
  teacherDialogVisible.value = true;
};

// 编辑教师
const handleEditTeacher = (row) => {
  isEditingTeacher.value = true;
  teacherForm.teacherId = row.teacherId;
  teacherForm.teacherName = row.teacherName;
  teacherForm.title = row.title;
  teacherForm.email = row.email;
  teacherForm.research = row.research;
  teacherForm.office = row.office;
  teacherForm.picture = row.picture;
  teacherDialogVisible.value = true;
};

// 删除教师
const handleDeleteTeacher = (row) => {
  ElMessageBox.confirm('确定要删除这位教师吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.delete(`${apiBaseUrl.value}/adminTeacher/delete/?teacherId=${row.teacherId}`,{headers: {
        'Session': `${session}`, // 传递 session
      },
      });
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        loadTeachers();
      } else {
        ElMessage.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除教师错误:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }).catch(() => {});
};

// 添加学生
const handleAddStudent = () => {
  isEditingStudent.value = false;
  Object.keys(studentForm).forEach(key => {
    if (key === 'id') {
      studentForm[key] = null;
    } else if (key === 'sex') {
      studentForm[key] = 1; // 默认男性
    } else if (key === 'grade') {
      studentForm[key] = new Date().getFullYear(); // 默认当前年级
    } else if (key === 'position') {
      studentForm[key] = '成员'; // 默认职位
    } else if (key === 'attendTimeDate') {
      // 设置今天的日期为YYYY-MM-DD格式
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      studentForm[key] = `${year}-${month}-${day}`;
    } else if (key === 'briInfo') {
      studentForm[key] = '在读'; // 默认状态
    } else {
      studentForm[key] = '';
    }
  });
  studentDialogVisible.value = true;
};

// 编辑学生
const handleEditStudent = (row) => {
  isEditingStudent.value = true;
  
  // 复制数据到表单
  Object.keys(studentForm).forEach(key => {
    if (key === 'picture') {
      studentForm.picture = row.picture || '';
    } else if (key === 'attendTimeDate') {
      // 如果attendTime是数组，转换为YYYY-MM-DD格式
      if (row.attendTime && row.attendTime.length === 3) {
        const year = row.attendTime[0];
        const month = String(row.attendTime[1]).padStart(2, '0');
        const day = String(row.attendTime[2]).padStart(2, '0');
        studentForm.attendTimeDate = `${year}-${month}-${day}`;
      } else if (typeof row.attendTime === 'string') {
        // 如果是字符串格式，直接使用
        studentForm.attendTimeDate = row.attendTime;
      } else {
        studentForm.attendTimeDate = '';
      }
    } else {
      studentForm[key] = row[key];
    }
  });
  
  studentDialogVisible.value = true;
};

// 删除学生
const handleDeleteStudent = (row) => {
  ElMessageBox.confirm('确定要删除这位学生吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 使用正确的API接口和DELETE方法
      const response = await axios.delete(`${apiBaseUrl.value}/adminUserInfo/delete/?id=${row.id}`,{headers: {
        'Session': `${session}`, // 传递 session
      },
      });
      
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        loadStudents();
      } else {
        ElMessage.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除学生错误:', error);
      console.log('请求URL:', `${apiBaseUrl.value}/adminUserInfo/delete/?id=${row.id}`);
      ElMessage.error('网络错误，请稍后重试');
    }
  }).catch(() => {});
};

// 提交教师表单
const submitTeacher = () => {
  teacherFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 构建符合后端API格式的数据对象
        const teacherData = {
          teacherId: teacherForm.teacherId,
          teacherName: teacherForm.teacherName,
          title: teacherForm.title,
          email: teacherForm.email,
          picture: teacherForm.picture,
          research: teacherForm.research,
          office: teacherForm.office
        };
        
        console.log('提交教师数据:', teacherData);
        
        let response;
        if (isEditingTeacher.value) {
          // 编辑现有教师
          response = await axios.post(`${apiBaseUrl.value}/adminTeacher/saveOrUpdateInfo`, teacherData,{headers: {
            'Session': `${session}`, // 传递 session
          },
          });
        } else {
          // 添加新教师
          response = await axios.post(`${apiBaseUrl.value}/adminTeacher/saveOrUpdateInfo`, teacherData,{headers: {
            'Session': `${session}`, // 传递 session
          },
          });
        }
        
        if (response.data.code === 200) {
          ElMessage.success(isEditingTeacher.value ? '更新成功' : '添加成功');
          teacherDialogVisible.value = false;
          loadTeachers();
        } else {
          ElMessage.error(response.data.message || (isEditingTeacher.value ? '更新失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交教师数据错误:', error);
        ElMessage.error('网络错误，请稍后重试');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 提交学生表单 - 适配新的API接口
const submitStudent = () => {
  studentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 构建符合后端API格式的数据对象
        const studentData = {
          id: studentForm.id,
          studentId: studentForm.studentId || '',
          name: studentForm.name,
          specialty: studentForm.specialty,
          email: studentForm.email,
          picture: studentForm.picture,
          blog: studentForm.blog,
          direction: studentForm.direction,
          briInfo: studentForm.briInfo,
          position: studentForm.position,
          achievementsNum: studentForm.achievementsNum || 0,
          sex: studentForm.sex,
          grade: String(studentForm.grade),
          // 直接使用attendTimeDate字段，已经是YYYY-MM-DD格式
          attendTime: studentForm.attendTimeDate || ''
        };
        
        console.log('提交数据:', studentData); // 添加调试日志
        
        // 调用API接口
        const response = await axios.post(`${apiBaseUrl.value}/adminUserInfo/saveOrUpdateInfo`, studentData,{headers: {
          'Session': `${session}`, // 传递 session
        },
        });
        
        if (response.data.code === 200) {
          ElMessage.success(isEditingStudent.value ? '更新成功' : '添加成功');
          studentDialogVisible.value = false;
          loadStudents();
        } else {
          ElMessage.error(response.data.message || (isEditingStudent.value ? '更新失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交学生数据错误:', error);
        ElMessage.error('网络错误，请稍后重试');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 教师头像上传成功处理
const handleTeacherAvatarSuccess = (response) => {
  if (response.code === 200) {
    teacherForm.picture = response.data;
    ElMessage.success('头像上传成功');
    console.log('教师头像上传成功，URL:', response.data);
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 学生头像上传成功处理
const handleStudentAvatarSuccess = (response) => {
  if (response.code === 200) {
    studentForm.picture = response.data;
    ElMessage.success('头像上传成功');
    console.log('学生头像上传成功，URL:', response.data);
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('头像必须是图片格式！');
  }
  
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB！');
  }
  
  return isImage && isLt2M;
};

// 处理分页大小变化
const handleTeacherSizeChange = (size) => {
  teacherPagination.pageSize = size;
  loadTeachers();
};

const handleStudentSizeChange = (size) => {
  studentPagination.pageSize = size;
  loadStudents();
};

// 处理页码变化
const handleTeacherCurrentChange = (page) => {
  teacherPagination.currentPage = page;
  loadTeachers();
};

const handleStudentCurrentChange = (page) => {
  studentPagination.currentPage = page;
  loadStudents();
};

// 格式化年级显示
const formatGrade = (grade) => {
  return grade ? `${grade}级` : '';
};

// 页面初始化时加载数据
onMounted(() => {
  // 根据当前激活的选项卡加载数据
  if (activeTab.value === 'teachers') {
    loadTeachers();
  } else {
    loadStudents();
  }
  
  // 为截断文本添加工具提示，使用原生DOM方式
  nextTick(() => {
    const truncatedTexts = document.querySelectorAll('.truncate-text');
    truncatedTexts.forEach(el => {
      if (el.scrollWidth > el.clientWidth) {
        el.setAttribute('title', el.textContent);
      }
    });
  });
});
</script>

<template>
  <div class="members-container">
    <div class="page-header">
      <h1>成员信息管理</h1>
    </div>

    <!-- 选项卡切换老师/学生管理 -->
    <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
      <el-tab-pane label="教师管理" name="teachers">
        <div class="control-panel">
          <el-button type="primary" @click="handleAddTeacher">添加教师</el-button>
        </div>

        <!-- 教师列表 -->
        <el-table
          :data="teacherList"
          style="width: 100%"
          border
          v-loading="teachersLoading"
        >
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column prop="teacherName" label="姓名" width="120" />
          <el-table-column prop="title" label="职称" width="120" />
          <el-table-column prop="email" label="邮箱" min-width="200" />
          <el-table-column prop="research" label="研究方向" min-width="250" />
          <el-table-column prop="office" label="办公室" width="150" />
          <el-table-column label="头像" width="120">
            <template #default="scope">
              <el-image
                v-if="scope.row.picture"
                :src="scope.row.picture"
                style="width: 60px; height: 60px"
                fit="cover"
                :preview-src-list="[scope.row.picture]"
              />
              <el-avatar v-else style="width: 60px; height: 60px">{{ scope.row.teacherName?.charAt(0) }}</el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditTeacher(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteTeacher(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="teacherPagination.currentPage"
            v-model:page-size="teacherPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="teacherPagination.total"
            @size-change="handleTeacherSizeChange"
            @current-change="handleTeacherCurrentChange"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="学生管理" name="students">
        <div class="control-panel">
          <el-button type="primary" @click="handleAddStudent">添加学生</el-button>
          <div class="filter-container">
            <el-input
              v-model="studentSearch"
              placeholder="搜索学生姓名"
              clearable
              class="search-input"
              @clear="loadStudents"
              @input="debounceStudentSearch"
            />
            <el-select
              v-model="selectedGrade"
              placeholder="选择年级"
              clearable
              @change="handleGradeChange"
              class="grade-select"
            >
              <el-option
                v-for="year in availableGrades"
                :key="year"
                :label="`${year}级`"
                :value="year"
              />
            </el-select>
          </div>
        </div>

        <!-- 学生列表 -->
        <el-table
          :data="studentList"
          style="width: 100%"
          border
          v-loading="studentsLoading"
          @sort-change="handleSortChange"
        >
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column label="性别" width="60">
            <template #default="scope">
              {{ scope.row.sex === 1 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column label="年级" width="80" sortable="custom" prop="grade">
            <template #default="scope">
              {{ scope.row.grade + '级' }}
            </template>
          </el-table-column>
          <el-table-column prop="specialty" label="专业" min-width="150" />
          <el-table-column prop="email" label="邮箱" min-width="150" />
          <el-table-column prop="direction" label="研究方向" min-width="140" />
          <el-table-column prop="position" label="职位" width="100" />
          <el-table-column prop="achievementsNum" label="成果数" width="80" align="center" />
          <el-table-column prop="blog" label="博客链接" min-width="120">
            <template #default="scope">
              <a v-if="scope.row.blog" :href="scope.row.blog" target="_blank" class="blog-link">
                {{ scope.row.blog ? '查看博客' : '' }}
              </a>
            </template>
          </el-table-column>
          <el-table-column prop="briInfo" label="简介" min-width="140">
            <template #default="scope">
              <div class="truncate-text">{{ scope.row.briInfo }}</div>
            </template>
          </el-table-column>
          <el-table-column label="加入时间" width="120" sortable="custom" prop="attendTime">
            <template #default="scope">
              <span v-if="scope.row.attendTime && scope.row.attendTime.length === 3">
                {{ scope.row.attendTime[0] }}-{{ scope.row.attendTime[1] }}-{{ scope.row.attendTime[2] }}
              </span>
              <span v-else>未设置</span>
            </template>
          </el-table-column>
          <el-table-column label="头像" width="80">
            <template #default="scope">
              <el-image
                v-if="scope.row.picture"
                :src="scope.row.picture"
                style="width: 50px; height: 50px"
                fit="cover"
                :preview-src-list="[scope.row.picture]"
              />
              <el-avatar v-else style="width: 50px; height: 50px">{{ scope.row.name?.charAt(0) }}</el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditStudent(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteStudent(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="studentPagination.currentPage"
            v-model:page-size="studentPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="studentPagination.total"
            @size-change="handleStudentSizeChange"
            @current-change="handleStudentCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 教师编辑对话框 -->
    <el-dialog
      v-model="teacherDialogVisible"
      :title="isEditingTeacher ? '编辑教师信息' : '添加教师'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="teacherForm" label-width="100px" :rules="teacherRules" ref="teacherFormRef">
        <el-form-item label="姓名" prop="teacherName">
          <el-input v-model="teacherForm.teacherName" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="teacherForm.title" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" />
        </el-form-item>
        <el-form-item label="研究方向" prop="research">
          <el-input v-model="teacherForm.research" />
        </el-form-item>
        <el-form-item label="办公室" prop="office">
          <el-input v-model="teacherForm.office" />
        </el-form-item>
        <el-form-item label="头像">
          <div class="avatar-controls">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleTeacherAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              name="image"
            >
              <img v-if="teacherForm.picture" :src="teacherForm.picture" class="avatar-preview" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-actions">
              <div class="upload-tip">点击上传头像（建议尺寸400×400像素）</div>
              <el-button 
                type="warning" 
                size="small" 
                @click="teacherForm.picture = ''"
                :disabled="!teacherForm.picture"
              >
                使用默认头像
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="teacherDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTeacher" :loading="submitting">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 学生编辑对话框 -->
    <el-dialog
      v-model="studentDialogVisible"
      :title="isEditingStudent ? '编辑学生信息' : '添加学生'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="studentForm" label-width="100px" :rules="studentRules" ref="studentFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="studentForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input-number v-model="studentForm.grade" :min="2000" :max="2100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="专业" prop="specialty">
          <el-input v-model="studentForm.specialty" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" />
        </el-form-item>
        <el-form-item label="研究方向" prop="direction">
          <el-input v-model="studentForm.direction" />
        </el-form-item>
        <el-form-item label="博客链接" prop="blog">
          <el-input v-model="studentForm.blog" placeholder="如：https://www.csdn.net/" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="studentForm.position" placeholder="请选择职位" style="width: 100%">
            <el-option label="成员" value="成员" />
            <el-option label="副负责人" value="副负责人" />
            <el-option label="总负责人" value="总负责人" />
          </el-select>
        </el-form-item>
        <el-form-item label="加入时间">
          <el-date-picker
            v-model="studentForm.attendTimeDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="简介" prop="briInfo">
          <el-input v-model="studentForm.briInfo" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="头像">
          <div class="avatar-controls">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleStudentAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              name="image"
            >
              <img v-if="studentForm.picture" :src="studentForm.picture" class="avatar-preview" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-actions">
              <div class="upload-tip">点击上传头像（建议尺寸400×400像素）</div>
              <el-button 
                type="warning" 
                size="small" 
                @click="studentForm.picture = ''"
                :disabled="!studentForm.picture"
              >
                使用默认头像
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="studentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStudent" :loading="submitting">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>



<style lang="scss" scoped>
.members-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0 0 20px 0;
    }
  }
  
  .control-panel {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .filter-container {
      display: flex;
      gap: 10px;
      
      .search-input {
        width: 200px;
      }
      
      .grade-select {
        width: 120px;
      }
    }
  }
  
  .truncate-text {
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-controls {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .avatar-uploader {
      display: flex;
      justify-content: center;
      
      .avatar-preview {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 4px;
        max-width: 100%;  /* 确保图片不超过容器宽度 */
      }
      
      .avatar-uploader-icon {
        width: 100px;
        height: 100px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        font-size: 28px;
        color: #8c939d;
        display: flex;
        justify-content: center;
        align-items: center;
        
        &:hover {
          border-color: #409EFF;
        }
      }
    }
    
    .upload-actions {
      margin-top: 8px;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .el-button {
        margin-top: 8px;
      }
    }
  }
  
  /* 限制el-image组件中的图片大小 */
  :deep(.el-image) {
    img {
      max-width: 100%;
      max-height: 300px;
      object-fit: contain;
    }
  }
  
  /* 确保图片预览弹出层的大小控制 */
  :deep(.el-image-viewer__wrapper) {
    .el-image-viewer__img {
      max-width: 80vw;
      max-height: 80vh;
    }
  }
  
  .blog-link {
    color: #409EFF;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  /* 确保水平滚动条在表格内容超出时显示 */
  :deep(.el-table) {
    width: 100%;
    overflow-x: auto;
  }
}
</style>
